/**
 * mqtt@4.3.7
 */
const mqtt = require('mqtt')
M=require("ming_node")



class MingMqttClient{

    constructor({clientId,brokerUrl,topics,messageEvent}) {

        this.clientId=clientId;
        this.options = {
            connectTimeout: 4000, // 超时时间
            // 认证信息
            clientId: this.clientId,
            // username: '',
            // password: '',
        }
        this.messageEvent=messageEvent;
        this.topics=topics;
        this.brokerUrl=brokerUrl;

        this.init();
    }

    send(topic,jobject){
        sendMessage(topic,JSON.stringify(jobject));
    }

    sendMessage( topic,  msg){
       this.client.publish(topic,msg, {
            qos: 1,
            rein: false
        }, (error) => {
            if(!error){

            }
            console.log(error || topic+'发布成功')
        })
    }

    init(){

        this.client = mqtt.connect(this.brokerUrl, this.options);

        this.client.on('reconnect', (error) => {
            console.log('正在重连:', error)
        })

        this.client.on('error', (error) => {
            console.log('连接失败:', error)
        })

        this.client.on('connect', (e) => {
            console.log('成功连接服务器')
            // 订阅主题 下面的#是订阅XXXXX下面的所有主题
            for (let i=0;i<this.topics.length;i++){
                this.client.subscribe(this.topics[i], {
                    qos: 1
                }, (error) => {
                    if (!error) {
                        console.log('订阅成功')
                    }
                })
            }
        })

        this.client.on('message', (topic, message) => {
            this.messageEvent(topic, message.toString())
        })
    }

    install(app,args){

    }

}


module.exports = MingMqttClient;